package org.water.common.shiro.filter;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import org.water.base.entity.R;
import org.water.common.bind.method.ResultFormatReturnValue;
import org.water.common.exception.SysCode;


/**
 * 用户认证
 * 
 * @author qzy
 *
 */
public class UserAuthenticationFilter extends FormAuthenticationFilter {

	public UserAuthenticationFilter() {
		// TODO Auto-generated constructor stub
	}

	private static Logger log = LogManager.getLogger(UserAuthenticationFilter.class);

	/** 主要是针对登入成功的处理方法。对于请求头是AJAX的之间返回JSON字符串。 **/
	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
			ServletResponse response) throws Exception {
		return super.onLoginSuccess(token, subject, request, response);
	}
	/**
	 * 失败处理
	 */
	@Override
	protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request,
			ServletResponse response)  {
		if ("XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))) {// ajax请求
			
				String message = e.getClass().getSimpleName();
				//ResultBaseBean bean=new ResultBaseBean();
			    R result=new R();
			    result.setSuccess(false);
			    //bean.setData(result);
				if ("IncorrectCredentialsException".equals(message)) {
					result.setMsg("密码错误");
				} else if ("UnknownAccountException".equals(message)) {
					result.setMsg("账号不存在");
				} else if ("LockedAccountException".equals(message)) {
					result.setMsg("账号被锁定");
				} else {
					result.setMsg("未知错误");
				}
				try {
					ResultFormatReturnValue.instance().setResultValue(result, (HttpServletRequest) request, (HttpServletResponse) response);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			
			return false;
		}
		return super.onLoginFailure(token, e, request, response);
	}
	/**
	 * 否认访问
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		
		HttpServletRequest hrequest =(HttpServletRequest) request;
		if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                log.debug(hrequest.getSession().getId()+"执行登录操作");
                return executeLogin(request, response);
            } else {
                return true;
            }
        } else {
            HttpServletRequest req = (HttpServletRequest)request;
            HttpServletResponse resp = (HttpServletResponse) response;
            if(req.getMethod().equals(RequestMethod.OPTIONS.name())) {
                resp.setStatus(HttpStatus.OK.value());
                return true;
            }
 
            if (log.isTraceEnabled()) {
                log.trace("Attempting to access a path which requires authentication.  Forwarding to the " +
                        "Authentication url [" + getLoginUrl() + "]");
            }
            ResultFormatReturnValue.instance().setResultValue(R.instance().setCode(SysCode.unauthorized.getCode()).setMsg("登录超时"), (HttpServletRequest) request, (HttpServletResponse) response);
            return false;
        }
	}
	
}
